package com.asia5b.a5mall.goods.dialog

import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.goods.R
import com.asia5b.a5mall.goods.adapter.SkuAdapter
import com.asia5b.a5mall.goods.adapter.SkuCallBack
import com.asia5b.a5mall.goods.databinding.DialogGoodsSpecBinding
import com.asia5b.a5mall.middleware.base.SimpleDialogFragment
import com.asia5b.a5mall.middleware.event.CartDataChange
import com.asia5b.a5mall.middleware.logic.viewmodel.goods.GoodsSpecDFVM
import com.asia5b.a5mall.middleware.model.goods.Goods2SkuModel
import com.asia5b.a5mall.middleware.model.goods.Goods2SpecModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.*
import kotlinx.android.synthetic.main.dialog_goods_spec.*

/**
 * Created by zhangyuncai on 2020/1/11.
 * 商品属性
 */
@Route(path = ActCons.GoodsSpecDF)
class GoodsSpecDF : SimpleDialogFragment<GoodsSpecDFVM, DialogGoodsSpecBinding>() {
    override val viewModelClazz: Class<GoodsSpecDFVM>
        get() = GoodsSpecDFVM::class.java

    override fun getDataBinding(container: ViewGroup?): DialogGoodsSpecBinding {
        arguments?.let {
            if (it.containsKey("type")) {
                isAddCart = requireArguments().getBoolean("type", false)
            }
            if (it.containsKey("data")) {
                goodsDetail = requireArguments().getSerializable("data") as AbsGoodsModel
            }
            if (it.containsKey("selectGoods2SkuModel")) {
                selectGoods2SkuModel = requireArguments().getSerializable("selectGoods2SkuModel") as Goods2SkuModel
            }
            if (it.containsKey("goodsId")) {
                goodsId = it.getInt("goodsId", 0)
            }
        }

        return DialogGoodsSpecBinding.inflate(layoutInflater,container,false)
    }


    //是否加入购物车
    private var isAddCart = false
    private var skuList: ArrayList<Goods2SkuModel>? = null
    private var goodsDetail: AbsGoodsModel? = null
    private var goodsId = 0

    //已选中的sku
    private var selectGoods2SkuModel: Goods2SkuModel? = null

    /*todo Spec是Sku的子集*/
    private val mSkuRecyclerView by lazy { rv_goods_sku }

    //todo 每一种具体的属性值收集起来,例如红色,蓝色,20码,30码等等属性值
    private var mSkuDatas = arrayListOf<ArrayList<Goods2SpecModel>>()
    private val skuCallBack = object : SkuCallBack {
        override fun callback(yShaft: Int, spec_value_id: Int) {
            val checkInventory = goodsSpecHelper?.checkInventory(yShaft, spec_value_id) ?: false
            if (checkInventory) {
                mSkuAdapter.notifyDataSetChanged()
            }
            setGoodsView()
            if (goodsSpecHelper == null || goodsSpecHelper!!.currentGoods2SkuModel == null) {
                showMessage(getString(R.string.无库存))
            }
        }
    }
    private val mSkuAdapter by lazy {
        SkuAdapter(mSkuDatas)
    }

    /*todo 有库存的spec_id集合  例如属性组合 蓝色-20码对应的 属性id组合 10100-20200 组装成字符串*/
    private val hasQulityList = arrayListOf<String>()

    private var goodsSpecHelper: GoodsSpecHelper? = null

    /**
     * 设置加入购物车和立即购买按钮是否可以点击
     * @param enable true:可以点击,false提示无库存
     */
    fun setSubmitEnable(enable: Boolean) {
        if (skuList?.size == 1) {//如果只有一个sku
            bt_goodsdetail_submit.tag = null
        } else {
            bt_goodsdetail_submit.tag = (enable).judge(null, false)
        }

    }

    override fun initView() {


        plus_goodsdetail.openEditText()
        plus_goodsdetail.qty = 1
        plus_goodsdetail.setMinQty(1)
        plus_goodsdetail.setMaxQty(1000)
        bt_goodsdetail_submit.text = (isAddCart).judge(getString(R.string.加入购物车), getString(R.string.立即购买))
//        bt_goodsdetail_submit.setBackgroundResource((isAddCart).judge(R.drawable.rec1_t_org_5dp, R.drawable.rec1_t_blue_5dp))
        //默认不可点击
        setSubmitEnable(false)

        mSkuAdapter.callback = skuCallBack
        mSkuRecyclerView?.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = mSkuAdapter
        }
        setGoodsView()
    }

    fun setGoodsView() {
        goodsSpecHelper?.currentGoods2SkuModel?.run {
            //商品图片
            WImageLoader.displayImage(thumbnail, iv_goodsdetail_goodimg)
            this.spec_list?.getOrNull(0)?.thumbnail?.let { img ->//默认使用sku中第一个属性的图片
                if (!TextUtils.isEmpty(img)) {
                    WImageLoader.displayImage(img, iv_goodsdetail_goodimg)
                }
            }
            //商品价格
//            tv_goodsdetail_price.text = "¥ ${price}"
            CurrencyPriceBuilder3().run {
                textView = tv_goodsdetail_price
                price = goodsSpecHelper!!.currentGoods2SkuModel!!.price
                priceList = price_list
                buildBlue14_18()
            }
            //是否可以点击
            setSubmitEnable(true)
//            callBack?.callback(this)
            mSureClick?.invoke(this)
        }
        //todo 防止被选中的规格中没有库存,恢复默认图片/名称
        if (goodsSpecHelper == null || goodsSpecHelper!!.currentGoods2SkuModel == null) {
            goodsDetail?.run {
                //商品图片
                WImageLoader.displayImage(absGoodsImageUrl, iv_goodsdetail_goodimg)
                //商品价格
                CurrencyPriceBuilder3().run {
                    textView = tv_goodsdetail_price
                    price = goodsDetail!!.absGoodsPrice
                    priceList = absGoodsPriceList
                    buildBlue14_18()
                }
                //是否可以点击
                setSubmitEnable(false)
            }
        }
    }

    override fun initData() {
        mViewModel.getGoodsSku(goodsId)
    }

    override fun initEvent() {
        //todo 立即购买/加入购物车
        bt_goodsdetail_submit.setOnClickListener {
            if (it.tag != null) {
                showMessage(getString(R.string.无库存))
                return@setOnClickListener
            }
            var sku_id = 0
            if (skuList?.size == 1) {//只有一个sku
                sku_id = skuList!!.get(0).sku_id
            } else {
                sku_id = goodsSpecHelper!!.currentGoods2SkuModel.sku_id
            }

//            if (true) {
//                dddLog("sku_id:${sku_id}")
//                return@setOnClickListener
//            }

            if (isAddCart) {
                mViewModel.addCart(sku_id, plus_goodsdetail.qty, null)
            } else {
                mViewModel.buyNum(sku_id, plus_goodsdetail.qty, null)
            }
        }
        iv_goodsdetail_close.setOnClickListener {
            dismiss()
        }
    }

  override  fun startObserver() {
        mViewModel.addCartLiveData.observe(this, Observer {
            addCartResult()
        })
        mViewModel.buyNumLiveData.observe(this, Observer {
            buyNumResult()
        })
        mViewModel.getGoodsSkuLiveData.observe(this, Observer {
            getGoodsSkuResult(it)
        })
    }

    fun buyNumResult() {
        push(ActCons.OrderPlaceActivity, {
            it.withBoolean("isBuyNow", true)
        })
        dismiss()
    }

    fun getGoodsSkuResult(it: ArrayList<Goods2SkuModel>) {
        skuList = it
        if (!skuList.isNullOrEmpty()) {

            //todo 循环添加每一种属性 key = 每一种属性(例如颜色)
            val map = HashMap<Int, ArrayList<Goods2SpecModel>>()
            for (goods2SkuModel in skuList!!) {
                /*todo 将有库存的数据收集起来*/
                val specValueIdListText = goods2SkuModel.spec_value_id_list_text
                if (goods2SkuModel.enable_quantity > 0 || goodsDetail!!.absGoodsIsSelf) {//todo 自营设置都有库存
                    hasQulityList.add(specValueIdListText)
                    dddLog("属性组合:${specValueIdListText};库存:${goods2SkuModel.enable_quantity}")
                } else {
                    dddLog("属性组合:无库存,且不是自营商品")
                }
                //todo 循环添加每一种属性,将属性组合 蓝色-20码,蓝色-30码,红色-20码,红色-30码转换为蓝色-20码/30码,红色-20码/30码
                val spec_list = goods2SkuModel.spec_list
                if (!spec_list.isNullOrEmpty()) {
                    for (goods2SpecModel in spec_list!!) {
                        if (!(map.containsKey(goods2SpecModel.spec_id))) {
                            //todo 第一次创建属性集合并添加
                            map.put(goods2SpecModel.spec_id, arrayListOf(goods2SpecModel))
                        } else {
                            //todo 如果不是第一次就判断spec_value_id是否存在,不存在就添加
                            val specList_map = map[goods2SpecModel.spec_id]!!
                            var has = false
                            for (goods2SpecModel_map in specList_map) {
                                if (goods2SpecModel_map.spec_value_id == goods2SpecModel.spec_value_id) {
                                    has = true
                                    break
                                }
                            }
                            if (!has) {
                                //todo 如果不是第一次就判断spec_value_id是否存在,不存在就添加
                                specList_map.add(goods2SpecModel)
                            }
                        }
                    }

                }
            }
            mSkuDatas.clear()
            for (entry in map.entries) {
                mSkuDatas.add(entry.value!!)
            }
            mSkuAdapter.notifyDataSetChanged()

            goodsSpecHelper = GoodsSpecHelper(skuList, mSkuDatas, hasQulityList)
            for (arrayList in goodsSpecHelper!!.mCombList) {
                dddLog("打印:$arrayList")
            }

            //外面选中的,在这里恢复上次选中的
            if (selectGoods2SkuModel != null) {
                val comb = arrayListOf<Int>()
                selectGoods2SkuModel!!.spec_list?.forEach {
                    comb.add(it.spec_value_id)
                }
                val checkInventory = goodsSpecHelper!!.checkInventory(comb)
                if (checkInventory) {
                    goodsSpecHelper!!.findPrice(comb)
                }
            }

        }

        setGoodsView()
    }


    fun addCartResult() {
        showMessage(getString(R.string.加入购物车成功))
        getEventBus().post(CartDataChange())
        dismiss()
    }


    override val heightPercent: Double
        get() = 0.6
}